package gradle.common.redis.redisson;

import jakarta.annotation.Resource;
import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.NatMapper;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.misc.RedisURI;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.Objects;
import java.util.Optional;

/**
 * RedissonConfig
 */
@Data
@RefreshScope
@Configuration
@ConditionalOnClass(value = RedissonClient.class)
public class RedissonConfig {

    @Resource
    private RedisProperties redisProperties;


    /**
     * 注入 Redisson-Client Bean
     *
     * @return RedissonClient
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        Config config = new Config();
        // 集群配置
        RedisProperties.Cluster cluster = redisProperties.getCluster();
        if (Objects.isNull(cluster) || CollectionUtils.isEmpty(cluster.getNodes())) {
            throw new RuntimeException("Redisson client create failed!");
        }
        // 设置连接信息
        ClusterServersConfig clusterServersConfig = config.useClusterServers();
        // 设置节点信息
        cluster.getNodes().forEach(node -> clusterServersConfig.addNodeAddress("redis://" + node));
        // 设置集群用户名 & 密码
        Optional.ofNullable(redisProperties.getPassword()).ifPresent(password -> clusterServersConfig.setUsername(null).setPassword(password));

        // 创建客户端对象
        return Redisson.create(config);
    }


}
